package com.artezio.buyndrive.validator;

import com.artezio.buyndrive.domain.Users;
import com.artezio.buyndrive.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

/**
 * User: spolyakov
 * Date: 26.07.12
 * Time: 14:55
 */

@Component
public class RegistrationValidator implements Validator{

    @Autowired
    private UserService userService;

    @Override
    public boolean supports(Class<?> clazz) {
        return Users.class.isAssignableFrom(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {

        Users user = (Users) target;

        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email",
                "required", "Email must not be empty.");

        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password",
                "required", "Password must not be empty.");

        //проверка по email
        if ( userService.get(user.getEmail()) != null ){
            errors.rejectValue("email",
                "validation.exists", "Email is exist!");
        }
    }

    public void confirmPass(Object target, Errors errors, String confPass){

        Users Users = (Users) target;

        // проверка повтора пароля
        if( ! Users.getPassword().equals(confPass) ){
            errors.rejectValue("password",
                "password.notMatch", "Conf.Password not match.");
        }

    }
}
